<template>
  <div class="content">
    <div class="content-title">详情任务信息</div>
    <div class="content-box" v-if="formData.fid">
      <div class="urgency">
        紧急度:
        {{ formData.urgency || '-' }}
      </div>
      <div class="top">
        <div class="top-left">
          <div class="form-item">
            <span class="label">任务单号：</span><span>{{ formData.taskNum }}</span>
          </div>
          <div class="form-item">
            <span class="label">告警来源：</span
            ><span>{{ alarmSourceMap[formData.alarmSource] }}</span>
          </div>
          <div class="form-item">
            <span class="label">告警事项：</span
            ><span>{{ eventTypeMap[formData.eventType] }}告警</span>
          </div>
          <div class="form-video">
            <span class="label">告警视频:</span>
            <video
              ref="videoRef"
              :src="formData.alarmVideoUrl"
              width="200"
              height="120"
              autoplay
              controls
            ></video>
          </div>
          <!-- <div class="form-video">
          <span class="label">告警视频:</span>
          <div class="btn-group">
            <el-button type="primary" @click="showVideo">打开页面</el-button>
            <el-button type="primary" @click="catchPic">抓图</el-button>
          </div>
          <div class="btn-group">
            <el-button v-for="(item, index) in list" @click="clickItem(index)">
              {{ item.text }}
            </el-button>
          </div>
          <div class="video">
            <iframe class="video" ref="myIframe" width="80%" height="200px"></iframe>
          </div>
        </div> -->
        </div>
        <div class="top-right">
          <div class="form-item">
            <span class="label">关联告警单：</span><span>{{ formData.alarmNum }}</span>
          </div>
          <div class="form-item">
            <span class="label">告警等级：</span
            ><span>{{ formData.alarmLevel == '1' ? 'I' : 'II' }}级</span>
          </div>
          <div class="form-item">
            <span class="label">告警详情：</span><span>{{ formData.alarmContent }}</span>
          </div>
          <div class="form-image">
            <div class="label">告警图片:</div>
            <div class="imageBox">
              <div class="imageBox-item" v-for="(item, index) in picList" :key="index">
                <el-image
                  style="width: 120px; height: 120px"
                  :src="item"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="picList"
                  show-progress
                  :initial-index="4"
                  fit="cover"
                  @show="changeVisible(false)"
                  @close="changeVisible(true)"
                >
                </el-image>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="line"></div>
      <div class="bottom">
        <div class="bottom-left">
          <div class="form-item">
            <span class="label">派单模式:</span>
            <span>
              <el-radio-group v-model="formData.dispatchMode">
                <el-radio value="1">自动调配</el-radio>
                <el-radio value="2">手工指派</el-radio>
              </el-radio-group>
            </span>
          </div>
          <div class="form-item">
            <span class="label">任务处理人:</span>
            <el-input
              v-model="formData.dispatchUser"
              style="width: 200px"
              placeholder="请输入"
              disabled
            />
          </div>
          <div class="form-item">
            <span class="label">任务状态:</span>
            <el-input
              v-model="disposalStatusMap[formData.taskState]"
              style="width: 200px"
              placeholder="请输入"
              disabled
            />
          </div>
        </div>
        <div class="bottom-right">
          <div class="form-item">
            <span class="label">预分配人员:</span>
            <el-select
              style="width: 200px"
              clearable
              filterable
              v-model="formData.userId"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in prepareList"
                :key="index"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </div>
          <div class="form-item">
            <span class="label">派发时间:</span>
            <el-input
              v-model="formData.dispatchTime"
              style="width: 200px"
              disabled
              placeholder="请输入"
            />
          </div>
          <div class="form-item">
            <span class="label">完成时间:</span>
            <el-input
              v-model="formData.finishTime"
              disabled
              style="width: 200px"
              placeholder="请输入"
            />
          </div>
        </div>
      </div>

      <div class="form-item">
        <span class="label">备注:</span>
        <el-input
          v-model="formData.notes"
          style="width: 70%; height: 100px"
          placeholder="请输入"
          type="textarea"
        />
      </div>

      <div class="form-buttom">
        <el-button
          type="primary"
          :loading="saveLoading"
          @click="submitTask"
          :disabled="
            !hasPermission ||
            formData.taskState == 2 ||
            formData.status == 'C' ||
            formData.taskState == 3
          "
          >确认派单
        </el-button>
      </div>
    </div>
    <el-empty description="暂无数据" v-else />
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Delete } from '@element-plus/icons-vue'
import {
  getPatrolAlarmDetail,
  getPatrolUse,
  getRolePermissions,
  setDispatchTask,
  uploadImage
} from '@/api/api'
import { ElMessage } from 'element-plus'

const saveLoading = ref(false)
const route = useRoute()
const formData = ref({
  fid: '',
  alarmLevel: '',
  eventType: '',
  alarmContent: '',
  alarmVideoUrl: '',
  worker: '',
  notes: ''
})
const eventTypeMap = {
  1: '空栏巡查',
  2: '饲养',
  3: '生物资产端到端',
  4: '生物安全',
  5: '健康',
  6: '上市巡查'
}

const alarmSourceMap = {
  1: '系统上报',
  2: '人工上报'
}
const disposalStatusMap = {
  1: '未处置',
  2: '已处置'
}

const props = defineProps({
  fid: {
    type: String,
    default: ''
  },
  orgId: {
    type: String,
    default: ''
  }
})

// 任务中心获取派单权限接口
const hasPermission = ref(false)
const fetchRolePermissions = async () => {
  try {
    const res = await getRolePermissions({
      userId: route.query.userId,
      userRole: 'DigitalPatrolDispatcher',
      orgId: route.query.orgId
    })
    if (res.status) {
      hasPermission.value = res.data
    }
  } catch (error) {
    console.error('获取预分配人员失败:', error.message) // 更详细的错误信息
  }
}

// 获取预分配人员
const prepareList = ref([])
const fetchPatrolUse = async () => {
  try {
    const res = await getPatrolUse({
      orgId: props.orgId,
      patrolSpot: formData.value.patrolSpot
    })
    if (res && res.data) {
      prepareList.value = res.data
    }
  } catch (error) {
    console.error('获取预分配人员失败:', error.message) // 更详细的错误信息
  }
}

const fetchPatrolAlarmDetail = async () => {
  formData.value = {}
  imageList.value = []
  picList.value = []
  try {
    const res = await getPatrolAlarmDetail({
      fid: props.fid // 任务单id
    })
    if (res && res.data) {
      formData.value = res.data
      imageList.value = res.data.pictureUrl
      imageList.value.forEach((item) => {
        if (item.includes('fileserver')) {
          // 如果包含 "fileserver"，直接使用原路径
          picList.value.push(item)
        } else {
          // 否则拼接 VITE_IMG_URL
          picList.value.push(`${import.meta.env.VITE_IMG_URL}${item}`)
        }
      })
      fetchRolePermissions()
      fetchPatrolUse()
    }
  } catch (error) {
    console.error('获取告警详情失败:', error.message)
  }
}

watch(
  () => props.fid,
  (newValue, oldValue) => {
    if (newValue) {
      fetchPatrolAlarmDetail()
    }
  },
  { immediate: true }
)

const submitTask = async () => {
  saveLoading.value = true
  try {
    const res = await setDispatchTask({
      params: {
        fid: formData.value.fid,
        dispatchMode: formData.value.dispatchMode,
        userId: formData.value.userId,
        notes: formData.value.notes,
        picUrl: imageList.value
      }
    })
    if (res && res.status) {
      ElMessage({
        message: res.data,
        type: 'success'
      })
      fetchPatrolAlarmDetail()
    } else {
      ElMessage({
        message: res.message,
        type: 'error'
      })
    }
    saveLoading.value = false
  } catch (error) {
    console.error('获取告警详情失败:', error.message)
    saveLoading.value = false
  }
}

// 抓取视频
const picList = ref([])
const imageList = ref([])
const list = ref([])
const myIframe = ref(null)
const showVideo = () => {
  let rect = myIframe.value.getBoundingClientRect()
  myIframe.value.src = `https://t-mall.wens.com.cn//isv/wens/smartb/smartbAiVideo/base.html#/DigtalSpaceVideoPlayerForIframe?orgId=${route.query.orgId}&farmerId=${formData.value.cqRearerId}&iframeFixLeftOffset=${rect.left + window.scrollX}&iframeFixTopOffset=${rect.top + window.scrollY}`
}

// 生成当前时间
const getCurrentDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')

  const formattedDate = `${year}-${month}-${day}`
  console.log(formattedDate)
  return formattedDate
}

const catchPic = () => {
  if (picList.value.length == 3) {
    ElMessage({
      message: '最多抓取3张图片',
      type: 'warning'
    })
    return
  }
  myIframe.value.contentWindow.postMessage(
    {
      handle: 'catchPic'
    },
    '*'
  )
}

const deletePic = (index) => {
  picList.value.splice(index, 1)
  imageList.value.splice(index, 1)
}

const changeVisible = (flag) => {
  console.log('changeVisible', flag)
  myIframe.value.contentWindow.postMessage(
    {
      handle: 'changeVisible',
      data: flag
    },
    '*'
  )
}

const clickItem = (index) => {
  // 打开对应视频
  myIframe.value.contentWindow.postMessage(
    {
      handle: 'playVideo',
      data: index
    },
    '*'
  )
}

// 添加水印
const addWatermark = async (base64Image) => {
  const img = new Image()
  img.src = base64Image
  await new Promise((resolve) => (img.onload = resolve))

  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')

  canvas.width = img.width
  canvas.height = img.height

  // 绘制原始图片
  ctx.drawImage(img, 0, 0)

  // 添加多行水印文字（右下角）
  ctx.fillStyle = 'red' // 水印颜色
  ctx.font = '20px Arial'
  ctx.textAlign = 'right'
  ctx.textBaseline = 'bottom'

  const watermarkLines = [
    `养户:${formData.value.rearerName}`,
    `群号:${formData.value.flockNumber}`,
    `时间:${getCurrentDate()}`
  ]
  const lineHeight = 25 // 行高
  const startX = canvas.width - 20 // 右侧留白
  let startY = canvas.height - 20 // 底部留白

  watermarkLines.forEach((line) => {
    ctx.fillText(line, startX, startY)
    startY -= lineHeight
  })
  return canvas.toDataURL('image/png')
}

function base64ToFile(base64Image, filename) {
  // 步骤1: 去除 Base64 的 data URL 前缀
  const base64Data = base64Image.replace(/^data:image\/\w+;base64,/, '')

  // 步骤2: 解码 Base64 数据为二进制字符串
  const binaryString = atob(base64Data)

  // 步骤3: 转换为 Uint8Array
  const len = binaryString.length
  const bytes = new Uint8Array(len)
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i)
  }

  // 步骤4: 创建 Blob 对象
  const blob = new Blob([bytes.buffer], { type: 'image/jpeg' }) // 根据实际图片类型修改 MIME 类型

  // 步骤5: 创建 File 对象
  const file = new File([blob], filename, { type: 'image/jpeg' })

  return file
}

// onMounted(async () => {
//   // 接收监听
//   window.addEventListener('message', async (event) => {
//     if (!event.data) {
//       return
//     }
//     if (event.data.code == '100') {
//       // 接收返回的可播放的列表
//       list.value = event.data.msg
//     } else if (event.data.code == '101') {
//       const base64 = `data:image/*;base64,${event.data.msg}`
//       // 添加水印
//       const watermarkedBase64 = await addWatermark(base64)
//       const blob = base64ToFile(watermarkedBase64, 'test.jpg')
//       const res = await uploadImage(blob)
//       picList.value.push(`${import.meta.env.VITE_IMG_URL}${res.data[0]}`)
//       imageList.value.push(res.data[0])
//     } else if (event.data.code == '003') {
//       ElMessage({
//         message: event.data.msg,
//         type: 'warning'
//       })
//     } else {
//       console.log(event.data.msg)
//     }
//   })
// })
</script>

<style scoped lang="scss">
.content {
  height: 100%;
  display: flex;
  flex-direction: column;

  &-title {
    font-weight: bold;
    font-size: 16px;
    margin-bottom: 20px;
  }
  &-box {
    position: relative;
    color: #fff;
    .urgency {
      position: absolute;
      right: 30px;
      top: 0;
      background-color: #ff4155;
      color: #fff;
      font-size: 16px;
      width: 140px;
      height: 40px;
      display: flex;
      padding: 5px 10px;
      justify-content: center;
      align-items: center;
      border-radius: 5px;
    }
    .top {
      width: 100%;
      display: flex;
      &-left {
        width: 50%;
      }
      &-right {
        width: 50%;
      }
    }
    .line {
      width: 100%;
      height: 3px;
      background-color: #2a4e7a;
      margin: 10px 0;
    }
    .bottom {
      width: 100%;
      display: flex;
      &-left {
        width: 50%;
      }
      &-right {
        width: 50%;
      }
    }
  }
}

.form {
  &-item {
    display: flex;
    align-items: start;
    margin-bottom: 10px;
    > span {
      margin-right: 10px;
    }
    .label {
      width: 80px;
    }
  }

  &-video {
    display: flex;
    flex-direction: column;
    margin-bottom: 10px;
    .label {
      margin-bottom: 10px;
    }
  }
  &-image {
    .label {
      margin-bottom: 10px;
    }
    .imageBox {
      display: flex;
      .delete {
        width: 10px;
        height: 10px;
      }
      &-item {
        margin-right: 10px;
      }
    }
  }

  &-buttom {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
  }
}
</style>
